package com.suptrack.dao.jpa;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.suptrack.dao.UserDao;
import com.suptrack.entity.Car;
import com.suptrack.entity.User;


@Stateless
public class JpaUserDao implements UserDao {

	@PersistenceContext(unitName="Suptracking")
    private EntityManager em;
	
	

	@Override
	public void addUser(User user) {
		em.persist(user);
		try
		{
		   em.flush();
		}
		catch (Exception e)
		{
		  System.out.println("*************** exception:"+e);
	
		}
		
	}

	
	@Override
	public void deleteUserbyId(long id) {

			User usertoremove = getUserInfo(id);
			usertoremove = em.merge(usertoremove);

			em.remove(usertoremove);
	
	}

	@Override
	public User getUserInfo(long _id) {
		User return_user;
	
			return_user = em.find(User.class, _id);
		
		return return_user;

	}

	@Override
	public List<User> getAllUser() {
		
		CriteriaBuilder criteriaBuilder=em.getCriteriaBuilder();
		  CriteriaQuery<User> criteriaQuery=criteriaBuilder.createQuery(User.class);
		  Root<User> root=criteriaQuery.from(User.class);
		  criteriaQuery.select(root);
		  TypedQuery<User> query=em.createQuery(criteriaQuery);
		  return query.getResultList();
		
	}

	@Override
	 public User getUserByName(String pseudo) {
	  
	  CriteriaBuilder cb = em.getCriteriaBuilder();
	  CriteriaQuery<User> query = cb.createQuery(User.class);
	  Root<User> user = query.from(User.class);
	  query.where(cb.equal(user.get("userName"), pseudo));

	  List<User> results =  em.createQuery(query).getResultList();
if( results.isEmpty() ){
	return null;
}
		
else
{
	  return results.get(0);
}
	 }
	public Long getNumberOfUser() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
				CriteriaQuery<Long> query = cb.createQuery(Long.class);
				query.select(cb.count(query.from(User.class)));
		return em.createQuery(query).getSingleResult();
	}


	@Override
	public User editUser(User user) {
		
		
		return  em.merge(user);
	}
}
